package com.lepu.app.fun.tool.bbwy;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.bbwy.bean.BeanToolBbwyNaiFen;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class BbwyMainFeedActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest {

	private static final String REQUEST_FINISH = "request_finish";
	private static final String REQUEST_NAI_FEN_LIST = "request_nai_fen_list";

	int mCurrentTab = 1;
	Button mFeedButton;
	Button mNaiFenButton;

	String mNaiFenID = "";
	int mNaiFenUnit = 150;
	
	ArrayList<BeanToolBbwyNaiFen> mDataList = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bbwy_activity_feed);

		UtilityBase.setStatusBarRes(this, R.color.color_bbwy, true);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("喂奶");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setTopbarBackground(R.color.color_bbwy);

		mFeedButton = (Button) findViewById(R.id.feedButton);
		mNaiFenButton = (Button) findViewById(R.id.naiFenButton);

		mFeedButton.setSelected(true);

		TextView naiFenTimeTextView = (TextView) findViewById(R.id.naiFenTimeTextView);
		TextView feedTimeTextView = (TextView) findViewById(R.id.feedTimeTextView);
		
		String currentDate = DateUtilBase.stringFromDate(new Date(), DateUtilBase.DATE_ALL);
		naiFenTimeTextView.setText(currentDate);
		feedTimeTextView.setText(currentDate);
	}

	private void submit() {

		String feedTime = "";
		if (mCurrentTab == 1) {
			TextView feedTimeTextView = (TextView) findViewById(R.id.feedTimeTextView);
			feedTime = feedTimeTextView.getText().toString();
		} else {
			TextView naiFenTimeTextView = (TextView) findViewById(R.id.naiFenTimeTextView);
			feedTime = naiFenTimeTextView.getText().toString();
		}

		if (TextUtils.isEmpty(feedTime)) {
			UIHelper.showToast(this, "请选择喂奶时间");
			return;
		}

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("RecordType", 1);
			
			params.put("FeedMilkTime", feedTime);
			params.put("MilkType", mCurrentTab);
			
			if (mCurrentTab == 2) {
				// naifen
				params.put("MilkPowderBrand", mNaiFenID);
				params.put("MilkAmount", mNaiFenUnit);
			} 

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getSaveBabyFeedingRecordUrl(), map,
				null, this, REQUEST_FINISH, true);
	}
	
	private void reqeustNaiFenList() {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post_main(Setting.getMilkPowderBrandListUrl(), map,
				null, this, REQUEST_NAI_FEN_LIST, true,false,true);
	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.feedButton:
		case R.id.naiFenButton:

			LinearLayout feedLayout = (LinearLayout) findViewById(R.id.feedLayout);
			LinearLayout naiFenLayout = (LinearLayout) findViewById(R.id.naiFenLayout);

			if (rid == R.id.feedButton) {
				mNaiFenButton.setSelected(false);

				mCurrentTab = 1;
				mFeedButton.setSelected(true);

				feedLayout.setVisibility(View.VISIBLE);
				naiFenLayout.setVisibility(View.GONE);
			} else {
				mFeedButton.setSelected(false);

				mNaiFenButton.setSelected(true);
				mCurrentTab = 2;

				feedLayout.setVisibility(View.GONE);
				naiFenLayout.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.feedTimeTextView:
			showFeedOrNaiFenTime();
			break;
		case R.id.naiFenNameTextView:
			
			if(mDataList != null && mDataList.size() > 0)
			{
				updateNaiFenList();
			}else{
				reqeustNaiFenList();
			}
			
			break;
		case R.id.naiFenUnitTextView:
			showNaiFenUnit();
			break;
		case R.id.naiFenTimeTextView:
			showFeedOrNaiFenTime();
			break;
		case R.id.finishButton:

			submit();
			break;

		default:
			break;
		}
	}
	
	private void showNaiFenUnit(){
		
		final ArrayList<Integer> dataArraylist = new ArrayList<Integer>();
		for(int i=10;i<=500;i+=5)
		{
			dataArraylist.add(i);
		}
		
		final String[] array = new String[dataArraylist.size()];
		int currentIndex = 0;

		for (int i = 0; i < dataArraylist.size(); i++) {
			array[i] = dataArraylist.get(i)+"ml";
		}

		final MyDialog dialog = new MyDialog(this);
		dialog.setSimpleSelectPicker(array, currentIndex)
				.setTitle("喂奶量")
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								WheelView wv_content = (WheelView) v
										.findViewById(R.id.simpleSelectPicker);
								int index = wv_content.getCurrentItem();

								TextView naiFenUnitTextView = (TextView) findViewById(R.id.naiFenUnitTextView);
								naiFenUnitTextView.setText(array[index]);

								mNaiFenUnit = dataArraylist.get(index);

							}
						}).create(null).show();
	}
	
	private void updateNaiFenList()
	{
		if(mDataList != null && mDataList.size() > 0)
		{
			final String[] array = new String[mDataList.size()];
			int currentIndex = 0;

			for (int i = 0; i < mDataList.size(); i++) {
				array[i] = mDataList.get(i).BrandName;
			}

			final MyDialog dialog = new MyDialog(this);
			dialog.setSimpleSelectPicker(array, currentIndex)
					.setTitle("奶粉品牌")
					.setNegativeButton(R.string.app_cancel,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {

								}
							})
					.setPositiveButton(R.string.app_ok,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {

									WheelView wv_content = (WheelView) v
											.findViewById(R.id.simpleSelectPicker);
									int index = wv_content.getCurrentItem();

									TextView naiFenNameTextView = (TextView) findViewById(R.id.naiFenNameTextView);
									naiFenNameTextView.setText(array[index]);

									mNaiFenID = mDataList.get(index).BrandID;

								}
							}).create(null).show();
		}
	}

	/**
	 * 选择喂奶或奶粉时间
	 */
	private void showFeedOrNaiFenTime() {
		new MyDialog(this)
				.setTitle("请选择喂奶时间")
				.setDateFullTimePicker(new Date())
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						// 如果是个数,则显示为"02"的样式
						WheelView wv_year = (WheelView) v
								.findViewById(R.id.yearFull);
						WheelView wv_month = (WheelView) v
								.findViewById(R.id.monthFull);
						WheelView wv_day = (WheelView) v
								.findViewById(R.id.dayFull);

						WheelView wv_hour = (WheelView) v
								.findViewById(R.id.hourFull);
						WheelView wv_minute = (WheelView) v
								.findViewById(R.id.minuteFull);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
								+ "-"
								+ decimal.format((wv_month.getCurrentItem() + 1))
								+ "-"
								+ decimal.format((wv_day.getCurrentItem() + 1)
										);
						String time = decimal.format((wv_hour
										.getCurrentItem()))
								+ ":"
								+ decimal.format((wv_minute
										.getCurrentItem()));
						
						String date = text+" "+time;

						Date selectDate = DateUtilBase.dateFromString(date,
								DateUtilBase.DATE_ALL);
						long selectTime = selectDate.getTime();
						Date currentDate = DateUtilBase.dateFromString(
								DateUtilBase.stringFromDate(new Date(),
										DateUtilBase.DATE_ALL),
								DateUtilBase.DATE_ALL);
						long currentTime = currentDate.getTime();

						if (selectTime > currentTime) {
							UIHelper.showToast(BbwyMainFeedActivity.this,
									R.string.bbwy_sleep_tip_3);
							return;
						}

						if (mCurrentTab == 1) {
							TextView feedTimeTextView = (TextView) findViewById(R.id.feedTimeTextView);
							feedTimeTextView.setText(date);
						} else {
							TextView naiFenTimeTextView = (TextView) findViewById(R.id.naiFenTimeTextView);
							naiFenTimeTextView.setText(date);
						}
					}
				}).create(null).show();
	}

	public void RequestComplete(Object object, Object data) {
		if(object.equals(REQUEST_FINISH))
		{
			hideProgressDialog();
			
			finish(true);
			
			BbwyMainActivity instance = (BbwyMainActivity) AppManager.getAppManager().getActivity(BbwyMainActivity.class);
			if(instance != null)
			{
				instance.request(false);
			}
		}else if(object.equals(REQUEST_NAI_FEN_LIST))
		{
			hideProgressDialog();
			
			mDataList = BeanToolBbwyNaiFen.parseListInfo((String)data);
			updateNaiFenList();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if(object.equals(REQUEST_FINISH))
		{
			hideProgressDialog();
		}else if(object.equals(REQUEST_NAI_FEN_LIST))
		{
			hideProgressDialog();
		}
	}
}
